package com.yefcion.survey.example;

import com.yefcion.survey.pojo.Dish;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;


/**
 * [Java8 Stream 使用指南](https://www.yuque.com/shimoind/hm4ydh/37cebcd6-afbe-4291-ab3e-421e39338d5a)
 */
public class StreamExam {

    /**
     * 筛选出卡路里小于 400 的菜肴
     * 对筛选出的菜肴进行一个排序
     * 获取排序后菜肴的名字
     */

    public List<String> beforeJava8(List<Dish> dishList) {
        List<Dish> lowCaloricDishes = new ArrayList<>();

        for (Dish dish : dishList) {
            if (dish.getCalories() < 400) {
                lowCaloricDishes.add(dish);
            }
        }

        Collections.sort(lowCaloricDishes, new Comparator<Dish>() {
            @Override
            public int compare(Dish o1, Dish o2) {
                return Integer.compare(o1.getCalories(), o2.getCalories());
            }
        });

        List<String> lowCaloricDishesName = new ArrayList<>();
        for (Dish d : lowCaloricDishes) {
            lowCaloricDishesName.add(d.getName());
        }
        return lowCaloricDishesName;
    }

    public List<String> whenJava8(List<Dish> dishList) {
        return dishList.stream()
                .filter(d -> d.getCalories() < 400)
                .sorted(comparing(Dish::getCalories))
                .map(Dish::getName)
                .collect(Collectors.toList());
    }
}
